import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'

import Exporter from 'containers/budget/budget-balance/exporter'
import ResizeTable from "components/resize-table";

import 'styles/budget/budget-balance/budget-balance-result.scss'
import { Table, Row, Col, Form, message, Button, Popover, Affix } from 'antd'
const FormItem = Form.Item;

import httpFetch from 'share/httpFetch'
import config from 'config'
import SlideFrame from 'components/slide-frame'
import BudgetBalanceAmountDetail from 'containers/budget/budget-balance/budget-balance-amount-detail'
import menuRoute from 'routes/menuRoute'

class BudgetBalanceResult extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      reloadLoading: false, //重新查询结果按钮loading
      budgetBalancePage: menuRoute.getRouteItem('budget-balance', 'key'),
      data: [],
      pagination: {
        total: 0
      },
      hasInitial: false,
      dimensionColumns: [],
      columns: [
        {title: messages('budget.key8'/*公司*/), width: 150, dataIndex: 'companyName', render: record => <Popover content={record}>{record}</Popover>},
        {title: messages('budget.key41'/*公司组*/), width: 150, dataIndex: 'companyGroupName', render: record => <Popover content={record}>{record}</Popover>},
        {title: messages('budget.key9'/*部门*/), width: 150, dataIndex: 'unitName', render: record => <Popover content={record}>{record}</Popover>},
        {title: messages('budget.key42'/*部门组*/), width: 150, dataIndex: 'unitGroupName', render: record => <Popover content={record}>{record}</Popover>},
        {title: messages('components.key845'/*成本中心组*/), width: 150, dataIndex: 'costCenterGroupName', render: record => <Popover content={record}>{record}</Popover>},
        {title: messages('budget.key43'/*员工*/), width: 150, dataIndex: 'employeeName', render: record => <Popover content={record}>{record}</Popover>},
        {title: messages('budget.key44'/*员工组*/), width: 150, dataIndex: 'employeeGroupName', render: record => <Popover content={record}>{record}</Popover>},
        {title: messages('budget.key45'/*预算项目类型*/), width: 150, dataIndex: 'itemTypeName', render: record => <Popover content={record}>{record}</Popover>},
        {title: messages('budget.key14'/*预算项目*/), width: 150, dataIndex: 'itemName', render: record => <Popover content={record}>{record}</Popover>},
        {title: messages('budget.key46'/*预算项目组*/), width: 150, dataIndex: 'itemGroupName', render: record => <Popover content={record}>{record}</Popover>},
        {title: messages('budget.key7'/*年度*/), dataIndex: 'periodYear', width: 150},
        {title: messages('budget.key165')/*半年度*/, dataIndex: 'periodSemiannual', width: 150},
        {title: messages('budget.key6'/*季度*/), dataIndex: 'periodQuarter', width: 150},
        {title: messages('budget.key5'/*期间*/), width: 150, dataIndex: 'periodName', render: record => <Popover content={record}>{record}</Popover>},
        {title: messages('common.currency'/**币种*/), dataIndex: 'currency', width: 100},
        {title: messages('budget.key1'/*预算额*/), width: 150, dataIndex: 'bgtAmount', render: (bgtAmount, record) => <a onClick={() => this.showSlideFrame(record, 'J')}>{this.filterMoney(bgtAmount)}</a>},
        {title: `TES实际报销单额`, width: 150, dataIndex: 'tesActualReimbursementAmount', render: (tesActualReimbursementAmount, record) => <a onClick={() => this.showSlideFrame(record, 'U', 'TR')}>{this.filterMoney(tesActualReimbursementAmount)}</a>},
        {title: `TES入账金额`, width: 150, dataIndex: 'tesActualReimbursementPostingAmount', render: (tesActualReimbursementPostingAmount, record) => <a onClick={() => this.showSlideFrame(record, 'U', 'TP')}>{this.filterMoney(tesActualReimbursementPostingAmount)}</a>},
        {title: `TES机票发生额`, width: 150, dataIndex: 'tesTicketAmountIncurred', render: (tesTicketAmountIncurred, record) => <a onClick={() => this.showSlideFrame(record, 'R', 'TI')}>{this.filterMoney(tesTicketAmountIncurred)}</a>},
        {title: `TES机票入账金额`, width: 150, dataIndex: 'tesTicketPostingAmount', render: (tesTicketPostingAmount, record) => <a onClick={() => this.showSlideFrame(record, 'R', 'TT')}>{this.filterMoney(tesTicketPostingAmount)}</a>},
        {title: `SAP全年累计发生额（截止到上月底）`, width: 160, dataIndex: 'sapAmount'},
        {title: messages('budget.key3'/*保留额*/), width: 150, dataIndex: 'flightRetentionAmount', render: (flightRetentionAmount, record) =>  <a onClick={() => this.showSlideFrame(record, 'R', 'TF')}>{this.filterMoney(flightRetentionAmount)}</a>},
        {title: messages('budget.key47'/*可用额*/), width: 150, dataIndex: 'expAvailableAmount', render: expAvailableAmount => this.filterMoney(expAvailableAmount)},
        {title: messages('budget.key48'/*预算进度*/), width: 150, dataIndex: 'schedule', render: schedule => (schedule * 100).toFixed(3) + '%'}
      ],
      scrollx: 150,
      condition: {
        companyNumber: 0,
        version: '',
        type: '',
        budgetStructure: '',
        budgetScenarios: ''
      },
      total: [],
      menuText: {
        totalNumber: messages('budget.key49'/*数据条数*/),
        bgtAmount: `${messages('budget.key50'/*总*/)}${messages('budget.key1'/*预算额*/)}`,
        tesActualReimbursementAmount: `TES实际报销单额`,
        tesActualReimbursementPostingAmount: `TES入账金额`,
        tesTicketAmountIncurred: `TES机票发生额`,
        tesTicketPostingAmount: `TES机票入账金额`,
        sapAmount: `SAP全年累计发生额（截止到上月底）`,
        flightRetentionAmount: `总保留额`,
        expAvailableAmount: `${messages('budget.key50'/*总*/)}${messages('budget.key47'/*可用额*/)}`,
      },
      page: 0,
      pageSize: 10,
      showSlideFrameFlag: false,
      slideFrameParam: {},
      titleMap: {
        J: `${messages('budget.key1'/*预算额*/)}${messages('budget.key2'/*明细*/)}`,
        R: `${messages('budget.key3'/*保留额*/)}${messages('budget.key2'/*明细*/)}`,
        U: `${messages('budget.key4'/*发生额*/)}${messages('budget.key2'/*明细*/)}`,
        TR: `TES实际报销单额明细`,
        TP: `TES入账金额明细`,
        TI: `TES机票发生额明细`,
        TT: `TES机票入账金额明细`,
        TF: `保留额明细`,
      },
      showExporterFlag: false
    };
  }

  componentWillMount(){
    httpFetch.get(`${config.budgetUrl}/api/budget/balance/query/header/${this.props.params.id}`).then(res => {
      let companyNumber = 0;
      res.data.queryLineList.map(item => {
        if(item.parameterCode === 'COMPANY')
          companyNumber = item.isAll ? messages('common.all') : messages('common.total1', {total: item.queryParameterList.length});
      });
      this.setState({
        condition: {
          companyNumber: companyNumber,
          version: res.data.versionName,
          type: res.data.amountQuarterFlagName,
          budgetStructure: res.data.structureName,
          budgetScenarios: res.data.scenarioName
        }
      })
    });
    this.getList();
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  getList = (isReload) => {
    let slideFrameParam = this.state.slideFrameParam;
    isReload && (slideFrameParam.data = {}); //点击【重新查询结果】按钮后，将明细清空
    this.setState({
      loading: true,
      reloadLoading: isReload,
      slideFrameParam
    });
    return httpFetch.get(`${config.budgetUrl}/api/budget/balance/query/results/${this.props.params.id}?page=${this.state.page}&size=${this.state.pageSize}`).then(res => {
      let data = [], total = [];
      if(res.data){
        data = res.data.queryResultList.map((item, index) => {
          item.key = this.state.page * this.state.pageSize + index;
          item.schedule = item.bgtAmount === 0 ? 0 : (item.expReserveAmount + item.expUsedAmount + item.bgtAdjustAmount) / item.bgtAmount;
          return item;
        });
        total = res.data.queryResultCurrencyList;
        let { dimensionColumns } = this.state;
        if(res.data.dimensionFiledMap && dimensionColumns.length === 0){
          let dimensionColumnsTemp = [];
          let dimensionFiledMap = res.data.dimensionFiledMap;
          Object.keys(dimensionFiledMap).map(dimensionIndex => {
            dimensionColumnsTemp.push({
              title: dimensionFiledMap[dimensionIndex],
              dataIndex: `dimension${dimensionIndex}Name`,
              index: dimensionIndex,
              render: record => <Popover content={record}>{record}</Popover>
            })
          });
          this.setState({ dimensionColumns: dimensionColumnsTemp });
        }
      }
      this.setState({
        loading: false,
        reloadLoading: false,
        data,
        total,
        pagination: {
          total: Number(res.headers['x-total-count']) ? Number(res.headers['x-total-count']) : 0,
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({
        loading: false
      })
    })
  };

  // record--当前数据；type--类型；detailType--详情类型，区分新增的几个字段
  showSlideFrame = (record, type, detailFlag) => {
    this.setState({
      showSlideFrameFlag: true,
      slideFrameParam: {
        dimensionColumns: this.state.dimensionColumns,
        type: type,
        data: record,
        title: this.state.titleMap[detailFlag || type],
        detailFlag,
      }
    })
  };

  renderMoney = (number, fixed) => {
    return <span className={number >= 0 ? 'green' : 'red'}>{this.filterMoney(number, fixed)}</span>
  };

  // 原来的逻辑
  // menuText: {
  //   totalNumber: messages('budget.key49'/*数据条数*/),
  //   bgtAmount: `${messages('budget.key50'/*总*/)}${messages('budget.key1'/*预算额*/)}`,
  //   expReserveAmount: `${messages('budget.key50'/*总*/)}${messages('budget.key3'/*保留额*/)}`,
  //   expUsedAmount: `${messages('budget.key50'/*总*/)}${messages('budget.key4'/*发生额*/)}`,
  //   expAvailableAmount: `${messages('budget.key50'/*总*/)}${messages('budget.key47'/*可用额*/)}`,
  //   bgtAdjustAmount: `${messages('budget.key50'/*总*/)}${messages('components.key1343'/*调整额*/)}`
  // },
  // {Object.keys(item).map((itemName, index) => {
  //   if(['expReserveAmount', 'expUsedAmount', 'bgtAdjustAmount', 'tesActualAmountIncurred'].includes(itemName)){
  //     return;
  //   }
  //   return itemName === 'currency' ? null : (
  //     <span className="currency-item-child" key={index}>
  //       <span className="ant-divider" />
  //       {this.state.menuText[itemName]} ：
  //       {itemName === 'totalNumber' ? item[itemName] : this.renderMoney(item[itemName])}
  //     </span>
  //   )
  // })}

  renderTotal = () => {
    return this.state.total.map((item, outerIndex) => {
      // 2024-01-04 新增修改
      // 字段展示顺序:总预算额>TES实际报销单额>TES入账金额 >TES机票发生额>TES机票入账金额>总保留额>总可用额
      return (
        <div className="currency-item" key={outerIndex}>
          {item.currency}
          {Object.keys(this.state.menuText).map((itemName, index) => {
            return (
              <span className="currency-item-child" key={index}>
                <span className="ant-divider" />
                {this.state.menuText[itemName]} ：
                {itemName === 'totalNumber' ? item[itemName] : this.renderMoney(item[itemName])}
              </span>
            )
          })}
        </div>
      )
    })
  };

  render(){
    const {
      columns, data, condition, loading, showSlideFrameFlag, slideFrameParam,
      budgetBalancePage, pagination, dimensionColumns, showExporterFlag, scrollx,
      reloadLoading
    } = this.state;

    return (
      <div className="budget-balance-result">
        <h3 className="header-title">{messages('budget.key51'/*查询结果*/)}</h3>
        <div className="header-info">
          <div className="header-info-title">{messages('budget.key52'/*查询条件*/)}</div>
          <div className="header-info-content">
            <Row gutter={40}>
              <Col span={8} className="info-block">
                <div className="info-title">{messages('budget.key8'/*公司*/)}:</div>
                <div className="info-content">{condition.companyNumber}</div>
              </Col>
              <Col span={8} className="info-block">
                <div className="info-title">{messages('budget.key53'/*预算版本*/)}:</div>
                <div className="info-content">{condition.version}</div>
              </Col>
              <Col span={8} className="info-block">
                <div className="info-title">{messages('budget.key54'/*金额 / 数量*/)}:</div>
                <div className="info-content">{condition.type}</div>
              </Col>
              <Col span={8} className="info-block">
                <div className="info-title">{messages('budget.key55'/*预算表*/)}:</div>
                <div className="info-content">{condition.budgetStructure}</div>
              </Col>
              <Col span={8} className="info-block">
                <div className="info-title">{messages('budget.key56'/*预算场景*/)}:</div>
                <div className="info-content">{condition.budgetScenarios}</div>
              </Col>
            </Row>
          </div>
        </div>


        <div className="table-header">
          <div className="table-header-title">{messages('common.total', {total: pagination.total ? pagination.total : '0'})}</div> {/* 共total条数据 */}
        </div>
        <ResizeTable columns={columns.concat(dimensionColumns)}
               dataSource={data}
               loading={loading}
               pagination={pagination}
               title={this.renderTotal}
               size="middle"
               bordered
               rowKey="key"
               className="budget-table"
               scroll={{ x: `${scrollx + dimensionColumns.length * 10}%` }}/>
        <SlideFrame content={BudgetBalanceAmountDetail}
                    show={showSlideFrameFlag}
                    onClose={() => this.setState({ showSlideFrameFlag: false })}
                    params={slideFrameParam}
                    title={slideFrameParam.title} width="70%"/>

        <Affix offsetBottom={0} className="bottom-bar">
          <Button type="primary" onClick={() => {this.context.router.push(budgetBalancePage.url)}}>{messages('budget.key57'/*返回修改参数*/)}</Button>
          <Button onClick={() => this.getList(true)} loading={reloadLoading} style={{ marginLeft: 10}}>{messages('budget.key33'/*重新查询结果*/)}</Button>
          <Button style={{ marginLeft: 10}} onClick={() => this.setState({ showExporterFlag: true })}>{messages('budget.key164')/*导出Excel*/}</Button>
        </Affix>

        <Exporter visible={showExporterFlag}
                  columns={columns}
                  dimensionColumns={dimensionColumns}
                  conditionId={this.props.params.id}
                  onCancel={() => this.setState({ showExporterFlag: false })}
                  afterClose={() => {this.setState({ showExporterFlag: false })}}/>

      </div>
    )
  }

}

BudgetBalanceResult.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps() {
  return {}
}

export default connect(mapStateToProps)(BudgetBalanceResult);
